package com.jxwifi.cloud.quickclean.app;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.AMapLocationQualityReport;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;

import cn.trinea.android.common.util.PreferencesUtils;

/**高德地图定位功能
 * Created by Administrator on 2019/5/16.
 */

public class LocationGaoDe extends PreferencesUtils {

    private String TAG = this.getClass().getSimpleName();
    private static Context mContext;
    private static AMapLocationClient locationClient = null;
    private static AMapLocationClientOption locationOption = null;

    private static boolean locatedSuccessed;
    private static Double Longitude=0.0;
    private static Double Latitude=0.0;//纬    度
    private static float Accuracy=0;//精    度
    private static String Province;//省
    private static String City;//市
    private static String CityCode;//城市编码
    private static String District;//区
    private static String AdCode;//区域 码
    private static String Address;//地    址
    public static  String formatAddress="";

    //初始化
    public void init(Context context){
        mContext=context;
        //初始化client
        locationClient = new AMapLocationClient(context.getApplicationContext());
        locationOption = getDefaultOption();
        //设置定位参数
        locationClient.setLocationOption(locationOption);
        // 设置定位监听
        locationClient.setLocationListener(locationListener);
    }

    /**
     * 开始定位
     * @since 2.8.0
     * @author Winter
     *
     */
    public static void startLocation(){
        //根据控件的选择，重新设置定位参数
        //resetOption();
        // 设置定位参数
        locationClient.setLocationOption(locationOption);
        // 启动定位
        locationClient.startLocation();

    }

    /**
     * 默认的定位参数
     * @since 2.8.0
     * @author Winter
     *
     */
    private AMapLocationClientOption getDefaultOption(){
        AMapLocationClientOption mOption = new AMapLocationClientOption();
        mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
        mOption.setGpsFirst(false);//可选，设置是否gps优先，只在高精度模式下有效。默认关闭
        mOption.setHttpTimeOut(30000);//可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
        //mOption.setInterval(30000);//可选，设置定位间隔。默认为2秒
        mOption.setNeedAddress(true);//可选，设置是否返回逆地理地址信息。默认是true
        mOption.setOnceLocation(true);//可选，设置是否单次定位。默认是false
        mOption.setOnceLocationLatest(false);//可选，设置是否等待wifi刷新，默认为false.如果设置为true,会自动变为单次定位，持续定位时不要使用
        AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);//可选， 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
        mOption.setSensorEnable(false);//可选，设置是否使用传感器。默认是false
        mOption.setWifiScan(true); //可选，设置是否开启wifi扫描。默认为true，如果设置为false会同时停止主动刷新，停止以后完全依赖于系统刷新，定位位置可能存在误差
        mOption.setLocationCacheEnable(true); //可选，设置是否使用缓存定位，默认为true
        mOption.setGeoLanguage(AMapLocationClientOption.GeoLanguage.DEFAULT);//可选，设置逆地理信息的语言，默认值为默认语言（根据所在地区选择语言）
        return mOption;
    }

    /**
     * 定位监听
     */
    AMapLocationListener locationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation location) {
            if (null != location) {
                StringBuffer sb = new StringBuffer();
                //errCode等于0代表定位成功，其他的为定位失败，具体的可以参照官网定位错误码说明
                if(location.getErrorCode() == 0){
                    Log.w("oushuhua","位置更新间隔");
                    sb.append("定位成功" + "\n");
                    sb.append("定位类型: " + location.getLocationType() + "\n");
                    sb.append("经    度    : " + location.getLongitude() + "\n");
                    sb.append("纬    度    : " + location.getLatitude() + "\n");
                    sb.append("精    度    : " + location.getAccuracy() + "米" + "\n");
                    sb.append("提供者    : " + location.getProvider() + "\n");

                    sb.append("速    度    : " + location.getSpeed() + "米/秒" + "\n");
                    sb.append("角    度    : " + location.getBearing() + "\n");
                    // 获取当前提供定位服务的卫星个数
                    sb.append("星    数    : " + location.getSatellites() + "\n");
                    sb.append("国    家    : " + location.getCountry() + "\n");
                    sb.append("省            : " + location.getProvince() + "\n");
                    sb.append("市            : " + location.getCity() + "\n");
                    sb.append("城市编码 : " + location.getCityCode() + "\n");
                    sb.append("区            : " + location.getDistrict() + "\n");
                    sb.append("区域 码   : " + location.getAdCode() + "\n");
                    sb.append("地    址    : " + location.getAddress() + "\n");
                    sb.append("兴趣点    : " + location.getPoiName() + "\n");

                    putString(mContext, "Longitude", String.valueOf(location.getLongitude()));
                    putString(mContext, "Latitude", String.valueOf(location.getLatitude()));
                    putString(mContext, "Accuracy", String.valueOf(location.getAccuracy()));
                    putString(mContext, "Province", location.getProvince());
                    putString(mContext, "city", location.getCity());
                    putString(mContext, "CityCode", location.getAdCode());
                    putString(mContext, "District", location.getDistrict());
                    putString(mContext, "AdCode", location.getAdCode());
                    putString(mContext, "Address", location.getAddress());
                    putString(mContext, "area", Regeocode()); //反编译获取区的信息，高德返回中没有这个字段所以需要反编译

                    //Log.i(TAG,"locationListener ==> city = "+location.getCity()+" CityCode = "+location.getAdCode()+" District = "+location.getDistrict()+" AdCode = "+location.getAdCode()+" Address = "+location.getAddress()+" area = "+Regeocode());

                    //定位完成的时间
                    sb.append("定位时间: " + LocationUtils.formatUTC(location.getTime(), "yyyy-MM-dd HH:mm:ss") + "\n");
                    //定位成功后停止定位请求
                    locationClient.stopLocation();
                    destroyLocation();
                    locatedSuccessed = true;
                   // refreshlocation();
                } else {
                    locatedSuccessed = false;
                    //定位失败
                    sb.append("定位失败" + "\n");
                    sb.append("错误码:" + location.getErrorCode() + "\n");
                    sb.append("错误信息:" + location.getErrorInfo() + "\n");
                    sb.append("错误描述:" + location.getLocationDetail() + "\n");

                }
                sb.append("***定位质量报告***").append("\n");
                sb.append("* WIFI开关：").append(location.getLocationQualityReport().isWifiAble() ? "开启":"关闭").append("\n");
                sb.append("* GPS状态：").append(getGPSStatusString(location.getLocationQualityReport().getGPSStatus())).append("\n");
                sb.append("* GPS星数：").append(location.getLocationQualityReport().getGPSSatellites()).append("\n");
                sb.append("* 网络类型：" + location.getLocationQualityReport().getNetworkType()).append("\n");
                sb.append("* 网络耗时：" + location.getLocationQualityReport().getNetUseTime()).append("\n");
                sb.append("****************").append("\n");
                //定位之后的回调时间
                sb.append("回调时间: " + LocationUtils.formatUTC(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss") + "\n");

                //解析定位结果，
                String result = sb.toString();
                Log.w("oushuhua",""+result);
            } else {
                locatedSuccessed = false;
                Log.w("oushuhua","定位失败 loc is null");
            }
        }

    };
    /**
     * 获取GPS状态的字符串
     * @param statusCode GPS状态码
     * @return
     */
    private String getGPSStatusString(int statusCode){
        String str = "";
        switch (statusCode){
            case AMapLocationQualityReport.GPS_STATUS_OK:
                str = "GPS状态正常";
                break;
            case AMapLocationQualityReport.GPS_STATUS_NOGPSPROVIDER:
                str = "手机中没有GPS Provider，无法进行GPS定位";
                break;
            case AMapLocationQualityReport.GPS_STATUS_OFF:
                str = "GPS关闭，建议开启GPS，提高定位质量";
                break;
            case AMapLocationQualityReport.GPS_STATUS_MODE_SAVING:
                str = "选择的定位模式中不包含GPS定位，建议选择包含GPS定位的模式，提高定位质量";
                break;
            case AMapLocationQualityReport.GPS_STATUS_NOGPSPERMISSION:
                str = "没有GPS定位权限，建议开启gps定位权限";
                break;
        }
        return str;
    }


    public static String Regeocode(){
        GeocodeSearch geocoderSearch = new GeocodeSearch(mContext);
        // 第一个参数表示一个Latlng(经纬度)，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
        RegeocodeQuery query = new RegeocodeQuery(new LatLonPoint(LocationGaoDe.getLatitude(),LocationGaoDe.getLongitude()), 200, GeocodeSearch.AMAP);
        geocoderSearch.getFromLocationAsyn(query);
        geocoderSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
            @Override
            public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {

                formatAddress= regeocodeResult.getRegeocodeAddress().getTownship();
                Log.w("client","result area"+regeocodeResult.getRegeocodeAddress().getTownship());
            }

            @Override
            public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

            }
        });
        //Log.i("LocationGaoDe","Regeocode() ==> formatAddress = "+formatAddress);
        return formatAddress;
    }



    /**
     * 销毁定位
     * @since 2.8.0
     * @author Winter
     */
    private void destroyLocation(){
        if (null != locationClient) {
            /**
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            locationClient.onDestroy();
            locationClient = null;
            locationOption = null;
        }
    }

    //经    度
    public static double getLongitude() {
        if(TextUtils.isEmpty(getString(mContext,"Longitude"))){
            return Longitude;
        }else{
            return Double.parseDouble(getString(mContext, "Longitude"));
        }
    }
    public static void putLongitude(double longitude) {
        putString(mContext, "Longitude", String.valueOf(longitude));
    }
    //纬    度
    public static double getLatitude() {
        if(TextUtils.isEmpty(getString(mContext,"Latitude"))){
            return Latitude;
        }else{
            return Double.parseDouble(getString(mContext, "Latitude"));
        }
    }

    public static void putLatitude(double latitude) {
        putString(mContext, "Latitude", String.valueOf(latitude));
    }
    //精    度
    public static Float getAccuracy() {
        if(TextUtils.isEmpty(getString(mContext,"Accuracy"))){
            return Accuracy;
        }else{
            return Float.parseFloat(getString(mContext, "Accuracy"));
        }
    }

    //省
    public static String getProvince() {
        if(TextUtils.isEmpty(getString(mContext,"Province"))){
            return Province;
        }else{
            return getString(mContext,"Province");
        }
    }
    //市
    public static String getCity() {
        if(TextUtils.isEmpty(getString(mContext,"city"))){
            return City;
        }else{
            return getString(mContext,"city");
        }
    }

    public static void putCity(String city) {
        putString(mContext, "city", city);
    }
    //区
    public static String getArea() {
        if(TextUtils.isEmpty(getString(mContext,"area"))){
            return formatAddress;
        }else{
            return getString(mContext,"area");
        }
    }
    public static void putArea(String city) {
        putString(mContext, "area", city);
    }

    //城市编码
    public static String getCityCode() {
        if(TextUtils.isEmpty(getString(mContext,"CityCode"))){
            return CityCode;
        }else{
            return getString(mContext,"CityCode");
        }
    }
    public static void putCityCode(String citycode) {
        putString(mContext, "CityCode", citycode);
    }

    //区
    public static String getDistrict() {
        if(TextUtils.isEmpty(getString(mContext,"District"))){
            return District;
        }else{
            return getString(mContext,"District");
        }
    }

    //区域 码
    public static String getAdCode() {
        if(TextUtils.isEmpty(getString(mContext,"AdCode"))){
            return AdCode;
        }else{
            return getString(mContext,"AdCode");
        }
    }

    //地址
    public static String getAddress() {
        if(TextUtils.isEmpty(getString(mContext,"Address"))){
            return Address;
        }else{
            return getString(mContext,"Address");
        }
    }

    public static boolean locatedSuccessed() {
        return locatedSuccessed;
    }

}
